package com.xuyuli.controller;

import com.xuyuli.domain.User;
import com.xuyuli.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;


@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/index.html")
    public String loginPage(){
        return "/login.jsp";
    }

    @RequestMapping(value = "/loginCheck.html")
    public ModelAndView loginCheck(HttpServletRequest request,LoginCommand loginCommand){
        boolean isValidUser = userService.hasMatchUser(loginCommand.getUserId(), loginCommand.getPassword());
        if (!isValidUser){
            return new ModelAndView("/login.jsp","error","用户名或密码错误");
        }else{
            User user = userService.findUserByUserId(loginCommand.getUserId());
            userService.loginSuccess(user);
            request.getSession().setAttribute("user",user);
            ModelAndView ma = new ModelAndView("/main.jsp");
            ma.addObject("user",user);
//            ma.getModel().put("user",user);
            return ma;
        }
    }

    @RequestMapping(value = "/register.html")
    public ModelAndView register(LoginCommand loginCommand){
        boolean isValidUser = userService.hasMatchUserId(loginCommand.getUserId());
        if (isValidUser){
            return new ModelAndView("/register.jsp","error","id已经注册错误");
        }else{
            userService.register(loginCommand.getUserId(),loginCommand.getUserName(),loginCommand.getPassword());
            return new ModelAndView("/login.jsp","success","注册成功，请开始登录");
        }
    }


}
